package com.tiancheng.trade.authserver.aop;

import com.tiancheng.trade.commom.core.utils.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 打印接口日志
 *
 * @author kellen
 * @date 2024/1/8
 */
@Component
@Aspect
@Slf4j
public class WebLogAspect {

    @Pointcut("execution(public * com.tiancheng.trade.authserver.controller..*.*(..))")
    public void webLog() {}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            // 开始打印请求日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 打印请求 url
            log.info("URL: {}, method:{}, Request Args: {}", request.getRequestURI(), request.getMethod(),
                    JsonUtil.logToJson(joinPoint.getArgs()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @AfterReturning(value = "webLog()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {
        try {
            // 开始打印请求日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 打印请求 url
            log.info("URL: {}, method:{}, Request Args: {}, Result: {}", request.getRequestURI(), request.getMethod(),
                    JsonUtil.toJsonString(joinPoint.getArgs()), result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
